package com.swang.pms.web.controller.manage;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.swang.pms.common.util.ImageCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.swang.pms.common.util.LoggerUtil;
import com.swang.pms.common.util.XSSUtil;
import com.swang.pms.model.constants.CommonConstants;
import com.swang.pms.model.dto.ManageMenuDto;
import com.swang.pms.model.entity.CurrentKey;
import com.swang.pms.model.entity.ManageUser;
import com.swang.pms.model.enums.AccountType;
import com.swang.pms.model.enums.Status;
import com.swang.pms.model.enums.UserType;
import com.swang.pms.model.vo.ResultMessage;
import com.swang.pms.service.manage.ManageMenuService;
import com.swang.pms.service.manage.ManageUserService;
import com.swang.pms.web.controller.BaseController;

/**
 * @ClassName: ManageLoginController
 * @Description: 登录服务控制层
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
@Controller
@RequestMapping
public class ManageLoginController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ManageLoginController.class);

    @Resource
    ManageMenuService           manageMenuService;

    @Resource
    ManageUserService           ManageUserService;

    //ImageCode                   imageCode;

    @RequestMapping("/login/page")
    @ResponseBody
    public ModelAndView page(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("/login/login");
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String index(ModelMap model) throws Exception {
        return "/login/login";
    }

    @RequestMapping(value = "/changePwdWin", method = RequestMethod.GET)
    public String changePwdWin(ModelMap model) {
        return "sys/win/changePwd";
    }

    @RequestMapping(value = "/changePwd")
    public @ResponseBody ResultMessage changePwd(HttpServletRequest request, @RequestParam("password") String password,
                                                 @RequestParam("oldPassword") String oldPassword) {
        ResultMessage result = new ResultMessage(true, "操作成功");
        ManageUser admin = this.getSessionUser(request);
        if (StringUtils.isBlank(password) || StringUtils.isBlank(oldPassword)) {
            result.change(false, "密码为空");
            return result;
        }
        if (!oldPassword.equals(admin.getPassword())) {
            result.change(false, "原密码不正确，请重新输入");
            return result;
        }
        ManageUser po = new ManageUser();
        po.setPassword(password);
        po.setId(admin.getId());
        try {
            this.ManageUserService.updateManagerUserByKeySelective(po);
        } catch (Exception e) {
            result.change(false, "操作失败");
            LoggerUtil.error(LOGGER, "login-changePwd error: {0}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request, ModelMap model) {
        ManageUser admin = getSessionUser(request);
        if (admin == null) {
            return "redirect:/login";
        }
        //查询菜单列表
        List<ManageMenuDto> menuList = this.manageMenuService.getLeftMenuList("admin".equals(admin.getUserName()) ? null : admin.getId());
        model.put("menuList", menuList);
        model.addAttribute("userName", admin.getUserName() == null ? "admin" : admin.getUserName());
        model.addAttribute("admin", admin.getUserType());
        return "sys/index";
    }

    @RequestMapping(value = "/loginOut") //登出
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/login";
    }

    @RequestMapping(value = "/console")
    public String page(HttpServletRequest request, ModelMap model) {
        return "sys/console";
    }

    @RequestMapping(value = "/loginTimeout") // 管理后台session超时处理页
    public String adminTimeOut() {
        return "common/loginTimeout";
    }

    @RequestMapping(value = "/loginPermission") // 没有权限
    public String loginPermission() {
        return "common/loginPermission";
    }

    @RequestMapping(value = "/loginVcode", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView loadImg(HttpServletRequest request, HttpServletResponse response) {
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        try {
            ServletOutputStream sos = response.getOutputStream();
            sos.close();
        } catch (IOException e) {
            LoggerUtil.error(LOGGER, "login-loadImg error: {0}", e.getMessage());
        }
        return null;
    }

    @RequestMapping(value = "/leftMenu") //菜单
    @ResponseBody
    public ResultMessage leftMenu(HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        ManageUser admin = getSessionUser(request);
        try {
            String dbStr = this.manageMenuService.getMenuTree(admin.getId(), admin.getUserName());
            dbStr = XSSUtil.stripXSS(dbStr);
            result.setContent(dbStr);
        } catch (Exception e) {
            result.change(false, "获取失败,错误信息:" + e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/loginIn")
    @ResponseBody
    public ResultMessage login(HttpServletRequest request, @ModelAttribute ManageUser admin) {
        ResultMessage result = new ResultMessage(true, "成功");
        try {
            String loginName = admin.getUserName();
            String pwd = admin.getPassword();
            String vcode = admin.getVcode();
            if (checkParam(request, result, loginName, pwd, vcode)) {
                return result;
            }
            List<ManageUser> dbAdmins = this.ManageUserService.listYunAdmin(admin);
            if (!checkAdminList(dbAdmins, result)) {
                return result;
            }
            ManageUser dbAdmin = dbAdmins.get(0);
            String isBlock = dbAdmin.getStatus();
            if (!checkAdminStates(isBlock, result)) {
                return result;
            }
            if (!pwd.equals(dbAdmin.getPassword())) {
                //result.change(false, "密码不正确");
                //return result;
            }
            //验证成功后，重置图片验证码，防止暴力入侵
            //request.getSession().removeAttribute(imageCode.getSessionKey());
            dbAdmin.setAccountType(AccountType.PLATFORM_ACCOUNT.getCode());
            if (!UserType.SYSADMIN.getCode().equals(dbAdmin.getUserType())) {
                //非超级管理员查询二级菜单权限至session
                dbAdmin.setMenusList(this.manageMenuService.getMenusById(dbAdmin.getId(), null));
            }
            setSessionUser(request, dbAdmin);//写入session
        } catch (Exception e) {
            result.change(false, "登录异常");
            LoggerUtil.error(LOGGER, "login-loginIn error: {0}", e.getMessage());
            return result;
        }
        return result;
    }

    private boolean checkAdminList(List<ManageUser> list, ResultMessage result) {
        if (CollectionUtils.isEmpty(list)) {
            result.change(false, "账号不存在");
            return false;
        }
        if (list.size() > 1) {
            result.change(false, "存在重复账号");
            return false;
        }
        return true;
    }

    private boolean checkAdminStates(String isBlock, ResultMessage result) {
        if (StringUtils.isNotBlank(isBlock) && !Status.ENABLED.getCode().equals(isBlock)) {
            if (Status.FREEZE.getCode().equals(isBlock)) {
                result.change(false, "账号处于锁定状态");
                return false;
            } else {
                result.change(false, "账号不存在");
                return false;
            }
        }
        return true;
    }

    private boolean checkParam(HttpServletRequest request, ResultMessage result, String loginName, String pwd, String vcode) {
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(vcode)) {
            result.change(false, "登陆信息不全");
            return true;
        }
       /* if (!vcode.equalsIgnoreCase((String) request.getSession().getAttribute(imageCode.getSessionKey()))) {
            result.change(false, "验证码不正确");
            return true;
        }*/
        return false;
    }

    @RequestMapping(value = "/current")
    @ResponseBody
    public void currentKey(HttpServletRequest request, HttpServletResponse response, @RequestBody CurrentKey currentKey) {
        request.getSession().setAttribute(CommonConstants.CURRENT_KEY, currentKey);
    }

}
